import styled from '@emotion/styled';
import { Button, Form, Select, SelectProps } from 'antd';

import DeleteIcon from '@/assets/icons/delete.svg';
import PlusIcon from '@/assets/icons/plus.svg';
import { colors } from '@/config/theme';

interface MappingProps {
  value?: Record<string, any>;
  onChange?: (value: Record<string, any>) => void;
  leftOptions: SelectProps['options'];
  rightOptions: SelectProps['options'];
}

const MappingItemDiv = styled.div`
  border: 1px solid transparent;
  transition: all 0.12s ease-in-out;
  position: relative;

  &:hover {
    border-color: ${colors.gray[300]};
    box-shadow: 0 0 6px ${colors.gray[300]};
  }
`;

export const Mapping = memo<MappingProps>((props) => {
  const [form] = Form.useForm();
  const [sourceList, setSourceList] = useState<string[]>([]);
  const [targetList, setTargetList] = useState<string[]>([]);

  const leftOptions = useMemo(() => {
    return (props.leftOptions || [])?.map((item) => ({
      ...item,
      disabled: sourceList.includes(String(item.value))
    })).sort(item => item.disabled ? 1 : -1);
  }, [props.leftOptions, sourceList]);

  const rightOptions = useMemo(() => {
    return (props.rightOptions || [])?.map((item) => ({
      ...item,
      disabled: targetList.includes(String(item.value))
    })).sort(item => item.disabled ? 1 : -1);;
  }, [props.rightOptions, targetList]);

  useEffect(() => {
    const keys = Object.keys(props.value || {});
    if (keys.length > 0) {
      form.setFieldsValue({
        list: keys.map((key) => ({
          source: props.value![key],
          target: key || ''
        }))
      });
    }
    setSourceList(Object.values(props.value || {}));
    setTargetList(keys);
  }, [form, props.value]);

  return (
    <Form
      onValuesChange={(_, value) => {
        const mapping = value.list.reduce((acc: Record<string, any>, item: Record<string, any>) => {
          acc[item?.target || ''] = item?.source || '';
          return acc;
        }, {});
        setSourceList(value.list.map((item: any) => item?.source || ''));
        setTargetList(value.list.map((item: any) => item?.target || ''));
        props.onChange?.(mapping);
      }}
      form={form}>
      <Form.List name="list">
        {(fields, { add, remove }) => {
          return (
            <div>
              <div className="form-header mb-8 flex bg-gray-50 py-8 justify-between">
                <div className="w-[40%] text-14--bold text-center">决策流入参</div>
                <div className="text-14--bold w-[40%] text-center">数据集字段</div>
                <div className="w-[30px]"></div>
              </div>
              {fields.map(({ key, name, ...restField }, index) => {
                return (
                  <MappingItemDiv key={key} className="flex justify-between h-50">
                    <div className="flex-1 flex justify-between items-center gap-12 pl-10">
                      <Form.Item
                        className="mb-0 h-30 flex-1"
                        {...restField}
                        name={[name, 'source']}
                        rules={[{ required: true, message: '请选择决策流入参' }]}>
                        <Select placeholder="请选择决策流入参" options={leftOptions} allowClear />
                      </Form.Item>
                      <div className="i-solar:shuffle-outline text-primary-500"></div>
                      <Form.Item
                        className="mb-0 h-30 flex-1"
                        {...restField}
                        name={[name, 'target']}
                        rules={[{ required: true, message: '请选择数据集字段' }]}>
                        <Select placeholder="请选择数据集字段" options={rightOptions} allowClear />
                      </Form.Item>
                    </div>
                    <div className="w-[40px] text-center flex items-center">
                      <DeleteIcon
                        className="cursor-pointer mx-12"
                        onClick={() => remove(index)}
                        width={16}
                        height={16}
                        fill={colors.red[500]}
                      />
                    </div>
                  </MappingItemDiv>
                );
              })}
              <Button type="dashed" className="mt-16" onClick={() => add()} block>
                <PlusIcon width={12} height={12} />
                新增字段映射
              </Button>
            </div>
          );
        }}
      </Form.List>
    </Form>
  );
});
